package com.agrimall.servlet.admin;

import com.agrimall.entity.User;
import com.agrimall.mapper.OrderMapper;
import com.agrimall.mapper.ProductMapper;
import com.agrimall.service.OrderService;
import com.agrimall.service.ProductService;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.OrderServiceImpl;
import com.agrimall.service.impl.ProductServiceImpl;
import com.agrimall.service.impl.UserServiceImpl;
import com.agrimall.util.MyBatisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员数据分析Servlet
 */
@WebServlet("/admin/statistics")
public class StatisticsServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private ProductService productService = new ProductServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if ("data".equals(action)) {
            // 返回JSON数据
            getStatisticsData(response);
        } else {
            // 显示页面
            request.getRequestDispatcher("/admin/statistics.jsp").forward(request, response);
        }
    }
    
    /**
     * 获取统计数据（JSON格式）
     */
    private void getStatisticsData(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 基础统计数据
            int userCount = userService.countAllUsers();
            int merchantCount = userService.countUsersByType(1);
            int productCount = productService.countAllProducts();
            int orderCount = orderService.countAllOrders();
            
            data.put("userCount", userCount);
            data.put("merchantCount", merchantCount);
            data.put("productCount", productCount);
            data.put("orderCount", orderCount);
            
            // 订单状态统计
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
                List<Map<String, Object>> orderStatusStats = orderMapper.countByStatus();
                
                // 格式化订单状态数据
                Map<String, Integer> orderStatusCount = new HashMap<>();
                Map<String, BigDecimal> orderStatusAmount = new HashMap<>();
                
                String[] statusNames = {"待付款", "待发货", "待收货", "已完成", "已取消", "售后中"};
                
                for (Map<String, Object> stat : orderStatusStats) {
                    Integer status = (Integer) stat.get("status");
                    Long count = ((Number) stat.get("count")).longValue();
                    BigDecimal amount = (BigDecimal) stat.get("totalAmount");
                    
                    if (status != null && status >= 0 && status < statusNames.length) {
                        orderStatusCount.put(statusNames[status], count.intValue());
                        orderStatusAmount.put(statusNames[status], amount != null ? amount : BigDecimal.ZERO);
                    }
                }
                
                data.put("orderStatusCount", orderStatusCount);
                data.put("orderStatusAmount", orderStatusAmount);
                
                // 总销售额
                BigDecimal totalSales = orderMapper.getTotalSales();
                data.put("totalSales", totalSales != null ? totalSales : BigDecimal.ZERO);
                
                // 商品分类统计
                ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
                List<Map<String, Object>> categoryStats = productMapper.countByCategoryGroup();
                
                Map<String, Integer> categoryCount = new HashMap<>();
                for (Map<String, Object> stat : categoryStats) {
                    String category = (String) stat.get("category");
                    Long count = ((Number) stat.get("count")).longValue();
                    if (category != null) {
                        categoryCount.put(category, count.intValue());
                    }
                }
                
                data.put("categoryCount", categoryCount);
                
            } finally {
                sqlSession.close();
            }
            
            // 用户类型统计
            int normalUserCount = userService.countUsersByType(0);
            int adminCount = userService.countUsersByType(2);
            
            Map<String, Integer> userTypeCount = new HashMap<>();
            userTypeCount.put("普通用户", normalUserCount);
            userTypeCount.put("商户", merchantCount);
            userTypeCount.put("管理员", adminCount);
            data.put("userTypeCount", userTypeCount);
            
            out.print(objectMapper.writeValueAsString(data));
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取统计数据失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(error));
        } finally {
            out.flush();
            out.close();
        }
    }
}

